package com.xt.base.util;

import java.io.File;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.web.context.WebApplicationContext;

/**
 * @author Hongbo Yang
 * @create-date:2007-6-21
 * @description:Spring工具类
 */
public class SpringUtil {
	
	public static ServletContext ServletContext = null;

	
	private static BeanFactory factory = null;
	private synchronized static void setFactory(){
		factory = new ClassPathXmlApplicationContext("applicationContext.xml");
	}
	
	/**
	 * 获取对象
	 * @param beanName 在Spring中配置的bean Name.
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T extends Object> T getBean(String beanName){
		if(factory==null) setFactory();
		return (T)factory.getBean(beanName);
	}
	
	/**
	 * 使用Spring AOP实现BeabFactory
	 * @param xml Spring AOP的配置文件。
	 * @return
	 */
	public synchronized static BeanFactory getXmlBeanFactory(File xml){
		Resource resources = new FileSystemResource(xml);
		factory = new XmlBeanFactory(resources);
		return factory;
	}
	
	/**
	 * 使用Spring AOP实现BeabFactory
	 * @param xml Spring AOP的配置文件相对路径。
	 * @return
	 */
	public synchronized static BeanFactory getXmlBeanFactory(String xml) {
		
		if(xml==null || "".equals(xml))
			xml = "applicationContext.xml";
		
		String path = (new SpringUtil()).getWebPageRealPath();
		path += "WEB-INF/";
		Resource resources = new FileSystemResource(path + xml);
		factory = new XmlBeanFactory(resources);
		return factory;
	}

	/**
	 * 取得应用程序根木路路径
	 * @return
	 */
	public String getWebPageRealPath() {
		String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
		if (path.indexOf("WEB-INF") > 0) {
			path = path.substring(0, path.indexOf("WEB-INF/"));
		}
		
		/*Tomcat下，路劲前多了一个 "/"*/
		if(path.indexOf("/")==0)
			path = path.replaceFirst("/", "");
		
		return path;
	}
	
	/** 使用与web系统同一套Spring的配置文件	 */
	private static WebApplicationContext webApplicationContext;
	
	public static void setWebApplicationContext(WebApplicationContext wact){
		webApplicationContext = wact;
	}
	
	@SuppressWarnings("unchecked")
	public static <T extends Object> T getWebBean(String beanName){
		return (T)webApplicationContext.getBean(beanName);
	}
}
